#!/usr/bin/perl6 

use JSON::Fast;

#`{
    {
        "user-list":[
            "yaominghua"
        ],
        "yaominghua":[
            {
                "ip":"192.169.126.100",
                "pass":"yaominghuaycl",
                "ext":""
            }
        ]
    }
}

my $default-config = $*HOME ~ '/.ftpuser.p6.cfg';

sub MAIN(Str :c(:$config-file) = "", *@file) {
    my $config-json;

    if $config-file.chars == 0 {
        say "Use default config path -> $default-config";
        $config-json = $default-config;
    }else{
        $config-json = $config-file;
    }

    my $json-path = IO::Path.new($config-json);

    if (!($json-path.e && $json-path.r)) {
        say "Config file not exist path -> $json-path";
        exit
    }
    my $json;

    try {
        $json = from-json($json-path.slurp());
        CATCH {
            default {
                "User config has error".say();
                "Stack ----->".say();
                ...
            }
        }
    }

    my @users = show-user-list($json, key => "user-list");

    if !defined(@users) {
        say "Json config not have user-list";
        exit
    }

    my $index = -1, my $count = +@users;

    while $count > 0 {
        input-prompt();
        $index = get($*IN);
        if $index < 0 || $index > $count {
            say "Error, please input again .....";
        }else{
            last;
        }
    }

    my %x =  get-user-info($json, user => @users[+$index]);

%x.say();

}

sub show-user-list($json, :$key) {
    if $json{$key}:exists == True {
        my @user-list = $json{$key}.split(' ');

        "Please chose a index".say();
        "User list \n--------------------".say();

        loop (my $i = 0;$i < +@user-list; $i++) {
            say ~$i ~ ".\t" ~ @user-list[$i];
        }

        "--------------------".say();

        return @user-list;
    }
}

sub get-user-info($json, :$user) {
    if $json{$user}:exists == True {
        return $json{$user};
    }
}

sub input-prompt($prompt = ">>>>>") {
    print $prompt;
}
